package com.redxiii.spike.util.message;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.redxiii.spike.api.command.Command;
import com.redxiii.spike.api.command.CommandParameters;
import com.redxiii.spike.api.command.CommandPattern;
import com.redxiii.spike.api.message.Message;

/**
 * @author Daniel Filgueiras
 * @since 19/06/2011
 */
public class SimpleMsgInterpreter {

	private static final Logger logger = LoggerFactory.getLogger(SimpleMsgInterpreter.class);
		
	public static Command getCommand(Message message, List<Class<? extends Command>> cmdClasses) {
		
		for (Class<? extends Command> clazz : cmdClasses) {
			CommandPattern patternCfg = clazz.getAnnotation(CommandPattern.class);
			CommandParameters paramCfg = clazz.getAnnotation(CommandParameters.class);
			
			if (patternCfg == null) {
				logger.warn("Command annotation missing {}",clazz);
				continue;
			}
			
			for (String regexp : patternCfg.patterns()) {
				Pattern pattern = Pattern.compile(regexp);
				Matcher matcher = pattern.matcher(message.toText());
				if (!matcher.find()) {
					continue;
				}
				
				Command command = null;
				
				try {
					command = clazz.newInstance();
				} catch (Exception e) {
					logger.error("Unable to create Command object for class: {}",clazz,e);
					return null;
				}
				
				
				if (paramCfg != null) {
					for (int index = 0; index < paramCfg.names().length; index++) {
						String name = paramCfg.names()[index];
						String param = (index < matcher.groupCount() ? matcher.group(index+1) : null);
						
						command.setParsedParameter(name, param);
					}
				}
				
				return command;
			}
		}
		
		return null;
		
	}
}
